﻿using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractForeEnd;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.Logs;
using HamcoWcs.Entitys.Logss;
using HamcoWcs.Models.Common;
using HamcoWcs.Models.Exceptions;
using HamcoWcs.Models.ForeEndModels.Basic;
using HamcoWcs.Models.Logs;
using HamcoWcs.Models.Logss;
using HamcoWcs.Models.OperationLogs;
using HamcoWcs.Service.Common;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace HamcoWcs.Main.Controllers.Wcs
{
    /// <summary>
    /// 日志接口
    /// </summary>
    public class LogController : BasicController
    {
        private readonly ILogViewService _logViewService;
        /// <summary>
        /// 
        /// </summary>
        public override string ControllerName => "LogController";
        /// <summary>
        /// 
        /// </summary>
        public LogController(WcsDbContext wcsDbContext, ILoggerService logger, ILogViewService logViewService)
            : base(logger, null, wcsDbContext)
        {
            _logViewService = logViewService;
        }

        #region Wcs 
        /// <summary>
        /// 查询设备异常日志
        /// </summary>
        /// <param name="queryDeviceErrorLog"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult DeviceError(QueryDeviceErrorLog queryDeviceErrorLog)
        {
            try
            {
                var result = _logViewService.GetDeviceErrorLog(queryDeviceErrorLog);
                return Json(result);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }

        /// <summary>
        /// 标记
        /// </summary>
        /// <param name="queryDeviceErrorLog"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult MarkDeviceErrorLog(MarkDeviceErrorLogModel model, [FromHeader] string userName = "UNK")
        {
            try
            {
                var e = _wcsDbContext.Set<DeviceErrorLog>().FirstOrDefault(x => x.Id == model.Id)
                    ?? throw new WarningException($"未找到对应的日志ID:{model.Id}");

                if (e.IsCsotError != model.Flag)
                {
                    e.IsCsotError = model.Flag;
                    _wcsDbContext.SaveChanges();
                    AddOperationLog(userName, $"DeviceErrorLog Id:{model.Id},IsCsotError修改为{model.Flag}");
                }

                return Json(ForeEndResult.Ok);
            }
            catch (WarningException ex)
            {
                return Warning(ex);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return UnknownExceptionResult();
            }
        }



        /// <summary>
        /// 查询登录日志
        /// </summary>
        /// <param name="queryLoginLog"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Login(QueryLoginLog queryLoginLog)
        {
            try
            {
                var result = _logViewService.GetLoginLog(queryLoginLog);
                return Json(result);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }

        /// <summary>
        /// 查询操作日志
        /// </summary>
        [HttpPost]
        public IActionResult Operation(QueryOperationLog queryOperationLog)
        {
            try
            {
                var result = _logViewService.GetOperationLog(queryOperationLog);
                return Json(result);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }

        /// <summary>
        /// 查询设备消息日志
        /// </summary>
        [HttpPost]
        public IActionResult DeviceMsg(QueryDeviceMsgLog queryDeviceMsgLog)
        {
            try
            {
                var result = _logViewService.GetDeviceMsgLog(queryDeviceMsgLog);
                return Json(result);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }


        /// <summary>
        /// 查询系统异常日志
        /// </summary>
        [HttpPost]
        public IActionResult SystemError(QuerySystemErrorLog querySystemErrorLog)
        {
            try
            {
                var result = _logViewService.GetSystemErrorLog(querySystemErrorLog);
                return Json(result);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }

        /// <summary>
        /// 查询WCS运行日志
        /// </summary>
        [HttpPost]
        public IActionResult WcsRun(QueryWcsRunLog queryWcsRunLog)
        {
            try
            {
                var result = _logViewService.GetWcsRunLog(queryWcsRunLog);
                return Json(result);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }

        ///// <summary>
        ///// 查询WMS消息文件
        ///// </summary>
        ///// <param name="queryWmsMsgLog"></param>
        ///// <returns></returns>
        //[HttpPost("WmsMsg")]
        //public IActionResult QueryWmsMsgLog(QueryWmsMsgLog queryWmsMsgLog)
        //{
        //    var result = _logViewService.GetWmsMsgLog(queryWmsMsgLog);
        //    return Json(result);
        //}




        #endregion

        /// <summary>
        /// 查询IO日志
        /// </summary>
        /// <param name="queryDeviceErrorLog"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult InterlockLog(PageSizeTime model)
        {
            try
            {
                var date = _wcsDbContext.Set<InterlockLog>()
                    .VagueWhereOut(model, out int count, out int pageCount)
                    .OrderByDescending(x=>x.CreatedTime)
                    .ToList();
                return Json(new ForeEndResult(date, count,pageCount));
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }

        ///// <summary>获取Mes通讯日志</summary>
        //[HttpPost]
        //public IActionResult GetMesCommunicationLog(MesMsgLogQueryDto query)
        //{
        //    try
        //    {
        //        var result =  _logViewService.GetMesCommunicationLog(query);
        //        return Json(result);
        //    }
        //    catch (Exception ex)
        //    {
        //        AddSystemLog(ex.Message);
        //        return QueryFailureResult();
        //    }
        //}

        ///// <summary>获取Mes通讯日志Bak</summary>
        //[HttpPost]
        //public async Task<IActionResult> GetMesCommunicationLogBak(MesMsgLogQueryDto query)
        //{
        //    try
        //    {
        //        var result = await _logViewService.GetMesCommunicationLogBak(query);
        //        return Json(result);
        //    }
        //    catch (Exception ex)
        //    {
        //        AddSystemLog(ex.Message);
        //        return QueryFailureResult();
        //    }
        //}


        /// <summary>查询通讯日志</summary>
        [HttpPost]
        public IActionResult GetCommunicationLog(UICommunicationLogQueryModel model)
        {
            try
            {
                var result = _logViewService.GetCommunicationLog(model);
                return Json(result);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }


        static string _communicationLogFolder;
        static LogController()
        {
            _communicationLogFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs", "communication_logs");
        }


        /// <summary>查询通讯日志(20230907更新为从文件查找)</summary>
        [HttpPost]
        public IActionResult GetCommunicationLogIO(UICommunicationLogIOQueryModel model)
        {
            var sw = Stopwatch.StartNew();
            try
            {
                if (model.Page <= 0) model.Page = 1;
                if (model.Size <= 0) model.Size = 100;

                if (model.StartTime == default || model.EndTime == default)
                    throw new WarningException("请输入时间");
                if (model.StartTime > model.EndTime)
                    throw new WarningException("请输入时间格式错误");

                List<string> datas = new List<string>();
                for (DateTime i = model.StartTime.Date; i <= model.EndTime.Date; i = i.AddDays(1))
                {
                    datas.Add(i.ToString("yyyyMMdd"));
                }

                var files = Directory.GetFiles(_communicationLogFolder);
                var needlogfiles = files.Where(x => datas.Contains(Path.GetFileName(x)));
                var logStrs = new List<string>();
                CompareInfo compare = CultureInfo.InvariantCulture.CompareInfo;
                foreach (var file in needlogfiles)
                {
                    logStrs.AddRange(System.IO.File.ReadAllLines(file)
                        .Where(x => x.ContainsIgnoreCase(model.MessageName))
                        .Where(x => x.ContainsIgnoreCase(model.Sender) || x.ContainsIgnoreCase(model.Receiver))
                        .Where(x => x.ContainsIgnoreCase(model.UnitId)));
                }

                var logs = logStrs.Select(x => JsonConvert.DeserializeObject<CommunicationLog>(x)).ToList();

                var query = logs.AsQueryable()
                    .WhereIf(x => x.UnitId.ContainsIgnoreCase(model.UnitId), !string.IsNullOrEmpty(model.UnitId))
                    .WhereIf(x => x.MessageName.ContainsIgnoreCase(model.MessageName), !string.IsNullOrEmpty(model.MessageName))
                    .WhereIf(x => x.Content.ContainsIgnoreCase(model.Content), !string.IsNullOrEmpty(model.Content))
                    .WhereIf(x => x.Return.ContainsIgnoreCase(model.Return), !string.IsNullOrEmpty(model.Return))
                    ;



                if (!string.IsNullOrEmpty(model.Sender) && !string.IsNullOrEmpty(model.Receiver))
                {
                    query = query.Where(x => x.Sender.ContainsIgnoreCase(model.Sender) || x.Receiver.ContainsIgnoreCase(model.Receiver));
                }
                else if (!string.IsNullOrEmpty(model.Sender))
                {
                    query = query.Where(x => x.Sender.ContainsIgnoreCase(model.Sender));
                }
                else if (!string.IsNullOrEmpty(model.Receiver))
                {
                    query = query.Where(x => x.Receiver.ContainsIgnoreCase(model.Receiver));
                }


                query = query.Where(x => x.CreatedTime >= model.StartTime && x.CreatedTime <= model.EndTime);

                var count = query.Count();

                var data = query.OrderByDescending(x => x.CreatedTime).Skip((model.Page - 1) * model.Size).Take(model.Size).ToList();
                sw.Stop();
                var pageCount = (count / (model.Size)) + 1;
                return Json(new ForeEndResult(data, count, pageCount)
                {
                    Details = $"用时：{sw.ElapsedMilliseconds} ms"
                });
            }
            catch (WarningException ex)
            {
                return Warning(ex);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }


        /// <summary>导出预先指定的表</summary>
        [NonAction]
        [HttpGet]
        public IActionResult GetLogs()
        {
            List<string> tables = new List<string>()
            {
                "device_error_log",
                "device_error_log_bak",
                "device_msg_log",
                "device_msg_log_bak",
                "login_log",
                "operation_log",
                "system_error_log",
                "wcs_run_log",
                "wcs_run_log_bak",
                "wms_msg_log",
                "wms_msg_log_bak",
            };

            try
            {
                var path = MysqlHelper.ExportDb("hamco_wcs", tables);
                return new FileStreamResult(new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite), "application/octet-stream")
                {
                    FileDownloadName = $"log{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.sql"
                };
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return Json(ForeEndResult.Fail("生成SQL文件失败"));
            }



        }


        /// <summary>通过表名导出日志</summary>
        [NonAction]
        [HttpGet]
        public IActionResult GetLogsByName(List<string> tables)
        {

            try
            {
                var path = MysqlHelper.ExportDb("hamco_wcs", tables);

                return new FileStreamResult(new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite), "application/octet-stream")
                {
                    FileDownloadName = $"log{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.sql"
                };
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return Json(ForeEndResult.Fail("生成SQL文件失败"));
            }
        }
    }
}
